﻿using EMall.Domain;
using System.Text.Json;

namespace EMall.ProductService.Categories
{
    public class CategoryUpdatedDomainEventHandler : Events.EventHandler<EntityUpdatedDomainEvent<Category>>
    {
        private readonly ICategoryRepository _categoryRepository;
        public CategoryUpdatedDomainEventHandler(
            ICategoryRepository categoryRepository)
        {
            _categoryRepository = categoryRepository;
        }
        public override async Task Handle(EntityUpdatedDomainEvent<Category> notification, CancellationToken cancellationToken)
        {
            var origin = JsonSerializer.Deserialize<Category>(notification.OriginJson);
            if (origin != null && origin.Code != notification.Entity.Code)
            {
                var children = await _categoryRepository.GetListByParentCodeAsync(origin.Code);
                foreach (var child in children)
                {
                    var newCode = child.Code.Replace(origin.Code, notification.Entity.Code);
                    child.UpdateCode(newCode);
                }
            }
        }
    }
}
